import React from 'react'
import { useNavigate } from 'react-router-dom'
import { Layout, theme, Dropdown, Avatar } from 'antd'
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UserOutlined
} from '@ant-design/icons'
import { connect } from 'react-redux'

function TopHeader(props) {
  const { Header } = Layout
  const {
    token: { colorBgContainer }
  } = theme.useToken()

  const navigate = useNavigate()
  const { role: { roleName }, username } = JSON.parse(localStorage.getItem('token'))

  const items = [
    {
      key: '1',
      label: roleName
    },
    {
      key: '2',
      danger: true,
      label: '退出登录'
    }
  ]

  const changeCollapsed = () => {
    props.changeCollapsed()
  }

  // 下拉菜单点击事件
  const onClick = ({ key }) => {
    if (key == 2) {
      navigate('/login')
      localStorage.removeItem('token')
    }
  }

  return (
    <Header style={{
      padding: '0 16px',
      background: colorBgContainer
    }}>
      {
      props.isCollapsed ? <MenuUnfoldOutlined onClick={() => changeCollapsed()} /> : <MenuFoldOutlined onClick={changeCollapsed} />
      }
      <div style={{ float: 'right' }}>
        <span style={{ marginRight: '10px' }}>欢迎 <span style={{ color: '#1890ff' }}>{username}</span> 回来</span>
        <Dropdown menu={{
          items,
          onClick
        }} >
          <Avatar icon={<UserOutlined />} size="large" />
        </Dropdown>
      </div>
    </Header>
  )
}

const mapStateToProps = (state) => {
  return {
    isCollapsed: state.CollapseReducer.isCollapsed
  }
}

const mapDispatchToProps = {
  changeCollapsed() {
    return {
      type: 'change_collapsed'
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(TopHeader)